package com.yixing.tech.entity.controller;

import com.alibaba.fastjson.JSONObject;
import com.yixing.tech.common.base.BaseControl;
import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.base.Rs;
import com.yixing.tech.common.security.context.SessionUser;
import com.yixing.tech.common.security.context.UserContext;
import com.yixing.tech.common.vo.s3.UserVO;
import com.yixing.tech.entity.entity.CustomActionParam;
import com.yixing.tech.entity.service.ICustomService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yixing tech
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/action")
public class ActionController extends BaseControl {
    @Resource
    private ICustomService customService;

    @PostMapping("/button")
    public Rs<Object> customAction(HttpServletResponse response, @RequestBody CustomActionParam param) throws BusinessException {
        SessionUser user = UserContext.getUser();
        param.setTenantId(user.getTenantId());
        param.setUserVO((UserVO) user);

        Object data = customService.customAction(response, param);
        if (data instanceof Boolean) {
            if (!(Boolean) data) {
                return Rs.ok();
            }
        }
        return Rs.ok(data);
    }

    @PostMapping("/button/file")
    public Rs<Object> customActionWithFile(HttpServletResponse response, @RequestPart MultipartFile file,
                                           @RequestParam(value = "contentParam") String contentParam) throws BusinessException {
        if (contentParam.endsWith(",")) {
            contentParam = contentParam.substring(0, contentParam.length() - 1);
        }
        CustomActionParam param = JSONObject.parseObject(contentParam, CustomActionParam.class);
        SessionUser user = UserContext.getUser();
        param.setTenantId(user.getTenantId());
        param.setUserVO((UserVO) user);
        param.setFile(file);
        Object data = customService.customAction(response, param);
        if (data instanceof Boolean) {
            if (!(Boolean) data) {
                return Rs.ok();
            }
        }
        return Rs.ok(data);
    }
    @PostMapping("/param")
    public Rs<Object> customOp(HttpServletResponse response, @RequestBody CustomActionParam param) throws BusinessException {
        Object o = customService.customOp(response, param);
        return Rs.ok(o);
    }
}
